package is.ru.honn.rupin.data;

import is.ru.honn.rupin.domain.User;
import is.ruframework.data.RuData;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: gmatt
 * Date: 19.10.2012
 * Time: 20:19
 *
 * An SQL implementation of the UserDataGateway interface
 */
public class UserData extends RuData implements UserDataGateway {
    /**
     * Adds a user to the database
     * @param user Passes the User to be added to the database to the function
     * @return The appropriate return key
     */
    public int add(User user) {
        SimpleJdbcInsert insertUser =
                new SimpleJdbcInsert(getDataSource())
                    .withTableName("ru_users")
                    .usingGeneratedKeyColumns("id");
        Map<String, Object> parameters = new HashMap<String, Object>(7);
        parameters.put("username", user.getUsername());
        parameters.put("firstName", user.getFirstName());
        parameters.put("lastName", user.getLastName());
        parameters.put("email", user.getEmail());
        parameters.put("password", user.getPassword());
        parameters.put("gender", user.getGender().name());
        int returnKey = 0;
        try
        {
            returnKey = insertUser.executeAndReturnKey(parameters).intValue();
        }
        catch (DataIntegrityViolationException ex)
        {
            log.warning("Duplicate entry");
        }
        return returnKey;
    }

    /**
     * Gets the user with the specified username
     * @param username the username to search for
     * @return the user with the given username
     */
    public User getUserByUsername(String username){
        JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
        return (User)queryContent.queryForObject("SELECT * FROM ru_users WHERE username=?",
                new UserRowMapper(), username);
    }
}
